// 添加词云分析功能
document.addEventListener('DOMContentLoaded', function() {
    const analyzeButton = document.getElementById('analyzeButton');
    if (analyzeButton) {
        analyzeButton.addEventListener('click', function() {
            const selectedProduct = document.getElementById('product-select').value;
            if (!selectedProduct) {
                showNotification('请先选择产品', 'warning');
                return;
            }
            
            // 显示加载状态
            document.getElementById('analysisLoading').style.display = 'block';
            document.getElementById('analysisResults').style.display = 'none';
            document.getElementById('analysisCard').style.display = 'block';
            
            // 请求AI分析
            fetch(`/api/products/${selectedProduct}/wordcloud/analyze`)
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        // 处理分析结果
                        displayAnalysisResults(data.analysis);
                    } else {
                        throw new Error(data.message || '分析失败');
                    }
                })
                .catch(error => {
                    showNotification('分析失败: ' + error.message, 'error');
                    document.getElementById('analysisCard').style.display = 'none';
                })
                .finally(() => {
                    document.getElementById('analysisLoading').style.display = 'none';
                });
        });
    }
});

/**
 * 显示分析结果
 * @param {Object} analysis 分析结果对象
 */
function displayAnalysisResults(analysis) {
    const resultsContainer = document.getElementById('analysisResults');
    
    // 显示高频关键词
    const keywordsContainer = document.getElementById('highFreqKeywords');
    keywordsContainer.innerHTML = '';
    
    if (analysis.top_keywords && analysis.top_keywords.length > 0) {
        const keywordsList = document.createElement('div');
        keywordsList.className = 'keyword-cloud';
        
        analysis.top_keywords.forEach((kw, index) => {
            const keyword = kw[0];
            const freq = kw[1];
            const keywordSpan = document.createElement('span');
            // 根据频率调整大小和颜色
            const size = Math.max(100, Math.min(180, 100 + (freq / analysis.top_keywords[0][1]) * 80));
            const hue = 200 - Math.floor((index / analysis.top_keywords.length) * 180);
            
            keywordSpan.textContent = keyword;
            keywordSpan.style.fontSize = `${size}%`;
            keywordSpan.style.color = `hsl(${hue}, 70%, 45%)`;
            keywordSpan.style.margin = '5px';
            keywordSpan.style.display = 'inline-block';
            keywordSpan.title = `频次: ${freq}`;
            
            keywordsList.appendChild(keywordSpan);
        });
        
        keywordsContainer.appendChild(keywordsList);
    } else {
        keywordsContainer.innerHTML = '<p class="text-muted">无高频关键词数据</p>';
    }
    
    // 显示关键词组
    const groupsContainer = document.getElementById('keywordGroups');
    groupsContainer.innerHTML = '';
    
    if (analysis.keyword_groups && analysis.keyword_groups.length > 0) {
        const groupsRow = document.createElement('div');
        groupsRow.className = 'row';
        
        analysis.keyword_groups.forEach(group => {
            const groupCol = document.createElement('div');
            groupCol.className = 'col-md-4 mb-3';
            
            const groupCard = document.createElement('div');
            groupCard.className = 'card h-100';
            
            const cardHeader = document.createElement('div');
            cardHeader.className = 'card-header bg-light';
            cardHeader.textContent = group.group_name;
            
            const cardBody = document.createElement('div');
            cardBody.className = 'card-body';
            
            // 添加描述
            const description = document.createElement('p');
            description.className = 'card-text text-muted small';
            description.textContent = group.description;
            cardBody.appendChild(description);
            
            // 添加关键词标签
            if (group.keywords && group.keywords.length > 0) {
                const keywordsDiv = document.createElement('div');
                keywordsDiv.className = 'mt-2';
                
                group.keywords.forEach(keyword => {
                    const badge = document.createElement('span');
                    badge.className = 'badge bg-info text-dark me-1 mb-1';
                    badge.textContent = keyword;
                    keywordsDiv.appendChild(badge);
                });
                
                cardBody.appendChild(keywordsDiv);
            } else {
                const noData = document.createElement('p');
                noData.className = 'text-muted small';
                noData.textContent = '无关键词数据';
                cardBody.appendChild(noData);
            }
            
            groupCard.appendChild(cardHeader);
            groupCard.appendChild(cardBody);
            groupCol.appendChild(groupCard);
            groupsRow.appendChild(groupCol);
        });
        
        groupsContainer.appendChild(groupsRow);
    } else {
        groupsContainer.innerHTML = '<p class="text-muted">无关键词组数据</p>';
    }
    
    // 显示分析摘要
    const summaryContainer = document.getElementById('analysisSummary');
    if (analysis.summary) {
        summaryContainer.innerHTML = `
            <div class="alert alert-info">
                <i class="fas fa-info-circle me-2"></i>
                ${analysis.summary}
            </div>
        `;
    } else {
        summaryContainer.innerHTML = '<p class="text-muted">无分析摘要数据</p>';
    }
    
    // 显示营销建议
    const suggestionsContainer = document.getElementById('marketingSuggestions');
    suggestionsContainer.innerHTML = '';
    
    if (analysis.marketing_suggestions && analysis.marketing_suggestions.length > 0) {
        const suggestionsList = document.createElement('ul');
        suggestionsList.className = 'list-group';
        
        analysis.marketing_suggestions.forEach(suggestion => {
            const item = document.createElement('li');
            item.className = 'list-group-item d-flex';
            
            const icon = document.createElement('i');
            icon.className = 'fas fa-lightbulb text-warning me-2 mt-1';
            
            const text = document.createElement('span');
            text.textContent = suggestion;
            
            item.appendChild(icon);
            item.appendChild(text);
            suggestionsList.appendChild(item);
        });
        
        suggestionsContainer.appendChild(suggestionsList);
    } else {
        suggestionsContainer.innerHTML = '<p class="text-muted">无营销建议数据</p>';
    }
    
    // 显示结果区域
    resultsContainer.style.display = 'block';
    
    // 平滑滚动到分析结果
    document.getElementById('analysisCard').scrollIntoView({
        behavior: 'smooth',
        block: 'start'
    });
} 